<?php
/**
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2017/5/20
 * Time: 16:16
 */
namespace app\admin\controller;
use app\models\Models;
use app\validate\AdminValidate;

/**
 * ------------------------------------------
 * Class Admin
 * @package app\admin\controller
 * 管理员管理类
 * ------------------------------------------
 */
class Admin extends Check{
    /**
     * 管理员列表
     * @return \think\response\View
     */
    public function adminList(){
        $get    = input('param.');
        $admin  = new Models('admin');
        $search = search($get,'a.username');    // 搜索
        $where  = $search['condition'].' and a.id != '.Models::GROUP_ADMIN;
        $join   = [['auth_group_access b','a.id=b.uid','left'],['auth_group c','b.group_id = c.id','left']];
        $field  = 'a.*,c.title ';
        $result = $admin->joinMany($join,$where,$field);
        return view('adminList',['result'=>$result,'display'=>$search['display']]);
    }

    /**
     * 添加管理员
     * @return array|\think\response\View
     */
    public function adminAdd(){
        if(request()->isPost()){
            $post   = input('param.');
            $admin  = new Models('admin');
            $access = new Models('auth_group_access');
            try{
                // 场景验证
                $validate = self::validate($post,'Admin.adminAdd');
                if(true !== $validate){
                    throw new \LogicException($validate,1000);
                }
                $add = [
                    'username'    => $post['username'],
                    'password'    => password_hash($post['password'],true),
                    'create_time' => time()
                ];
                if($post['group_id'] == Models::GROUP_BUSINESS){
                    $add['status'] = Models::STATUS_NOT_ACTIVE;
                }
                $admin->startTrans();
                // 添加管理员
                $uid = $admin->_add($add);
                // 关系表添加记录
                $bool = $access->_add(['uid'=>$uid,'group_id'=>$post['group_id']]);
                // 添加操作日志
                $log  = self::addLog('添加管理员-'.$post['username']);
                if(!$uid || false === $bool || !$log){
                    $admin->rollback();
                    throw new \LogicException('操作失败',1010);
                }
            }catch(\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            $admin->commit();
            return self::formatSuccessResult();
        }
        $group = new Models('auth_group');
        $list  = $group->_select(['id'=>['<>',Models::GROUP_ADMIN]]);
        return view('adminAdd',['list'=>$list]);
    }

    /**
     * @return array|\think\response\View
     * 修改管理员
     */
    public function adminSave(){
        if(request()->isPost()){
            $post   = input('param.');
            $access = new Models('auth_group_access');
            $bool   = $access->_save(['group_id'=>$post['group_id']],'uid ='.$post['uid']);
            // 添加操作日志
            $log    = self::addLog('修改管理员');
            if(false === $bool || !$log){
                throw new \LogicException('操作失败',1010);
            }
            return self::formatSuccessResult();
        }
        $get   = input('param.');
        $admin = new Models('admin');
        $group = new Models('auth_group');
        $info  = $admin->joinOne([['auth_group_access b','a.id = b.uid','left']],'a.id = '.$get['id'],'a.id,a.username,b.group_id');
        $list  = $group->_select(['id'=>['<>',Models::GROUP_ADMIN]]);
        return view('adminSave',['list'=>$list,'info'=>$info]);
    }

    /**
     * @return array
     * 改变管理员状态
     */
    /*public function adminStatus(){
        if(request()->isPost()){
            $post = input('param.');
            $admin = new Models('admin');
            try{
                $status = $post['status'] == Models::STATUS_ON ? Models::STATUS_OFF : Models::STATUS_ON;
                $bool   = $admin->_save(['id'=>$post['id'],'status'=>$status]);
                // 添加操作日志
                $username = $admin->getValue(['id'=>$post['id']],'username');
                $log = self::addLog('修改管理员-'.$username.'状态');
                if(false === $bool || !$log){
                    throw new \LogicException('操作失败',1010);
                }
                return self::formatSuccessResult(['status'=>$status]);
            }catch(\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
        }
    }*/

    /**
     * 启用
     * @return array
     */
    public function start(){
        if(request()->isAjax()){
            $post = input('param.');
            $admin = new Models('admin');
            try{
                $bool = $admin->setValue(['id'=>$post['id']],['status'=>Models::STATUS_ON]);
                if(!$bool){
                    throw new \Exception('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
    }

    /**
     * 停用
     * @return array
     */
    public function stop(){
        if(request()->isAjax()){
            $post = input('param.');
            $admin = new Models('admin');
            try{
                $bool = $admin->setValue(['id'=>$post['id']],['status'=>Models::STATUS_OFF]);
                if(!$bool){
                    throw new \Exception('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
    }

    /**
     * @return array|\think\response\View
     * 修改管理员密码
     */
    public function adminChangePassword(){
        $admin = new Models('admin');
        if(request()->isPost()){
            $post = input('param.');
            try{
                $password = password_hash($post['password'],true);
                $bool = $admin->_save(['id'=>$post['id'],'password'=>$password]);
                // 添加操作日志
                $username = $admin->getValue(['id'=>$post['id']],'username');
                $log  = self::addLog('修改管理员-'.$username.'密码');
                if(false === $bool || !$log){
                    throw new \LogicException('操作失败',1010);
                }
            }catch(\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $get  = input('param.');
        $info = $admin->_find($get['id']);
        return view('adminChangePassword',['info'=>$info]);
    }
}